package com.heima.behavior.service.impl;

import com.heima.behavior.config.CacheService;
import com.heima.behavior.service.ApUnlikesBehaviorService;
import com.heima.common.constants.user.UserRelationConstants;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApUnlikesBehaviorServiceImpl implements ApUnlikesBehaviorService {
    @Autowired
    CacheService cacheService;
    /**
     * 不喜欢
     *
     * @param unLikesBehaviorDto
     * @return
     */
    @Override
    public ResponseResult unLike(UnLikesBehaviorDto unLikesBehaviorDto) {
        //1.参数校验
        if (unLikesBehaviorDto==null||unLikesBehaviorDto.getArticleId()==null||checkParm(unLikesBehaviorDto)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.不喜欢数据保存
        Long articleId = unLikesBehaviorDto.getArticleId();
        Integer userId = user.getId();
        Short type = unLikesBehaviorDto.getType();
        if (type==0){
            //是否已点不喜欢
            Double score = cacheService.zScore(UserRelationConstants.BEHAVIOR_UNLIKE + userId, articleId.toString());
            if (score!=null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"已点不喜欢");
            }
            //保存不喜欢数据
            cacheService.zAdd(UserRelationConstants.BEHAVIOR_UNLIKE + userId, articleId.toString(),System.currentTimeMillis());
            log.info("保存不喜欢数据成功");
        }else {
            cacheService.zRemove(UserRelationConstants.BEHAVIOR_UNLIKE + userId, articleId.toString());
            log.info("删除不喜欢数据成功");
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private boolean checkParm(UnLikesBehaviorDto unLikesBehaviorDto) {
        Short type = unLikesBehaviorDto.getType();
        if (type<0||type>1){
            return true;
        }
        return false;
    }
}

